package server;

import command.server.CommandFactoryServer;
import command.server.CommandServer;
import command.server.LoginUserServer;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.MessageCommunication;
import model.User;

public class ClientThread extends Thread {

    private Socket clientSocket;
    private ObjectInputStream input;
    private ObjectOutputStream output;
    private User user;
    private boolean userActive = false;

    public ClientThread(Socket socket) {
        clientSocket = socket;
    }

    public ObjectInputStream getObjectInputStream() {
        return input;
    }

    public ObjectOutputStream getObjectOutputStream() {
        return output;
    }

    public void setUser(User u) {
        user = u;
    }

    public User getUser() {
        return user;
    }

    public void closeSession() {
        userActive = false;
        Server.removeUserActive(user);
    }

    public synchronized void executeCommand(String commandName) {
        CommandServer command = CommandFactoryServer.getCommand(commandName);
        command.execute(this);
    }

    @Override
    public void run() {
        userActive = true;
        try {
            output = new ObjectOutputStream(clientSocket.getOutputStream());
            input = new ObjectInputStream(clientSocket.getInputStream());
            while (userActive) {
                Object receiveCommand;
                receiveCommand = input.readObject();
                if (receiveCommand != null) {
                    MessageCommunication m = (MessageCommunication) receiveCommand;
                    if (m.getMessage().equals("loginuserserver")) {
                        LoginUserServer command = (LoginUserServer) CommandFactoryServer.getCommand(m.getMessage());
                        command.execute(this);
                        user = command.getFinalUser();
                        Server.addUserActive(command.getFinalUser(), this);
                    } else {
                        executeCommand(m.getMessage());
                    }
                }
            }
        } catch (ClassNotFoundException | IOException ex) {
            Logger.getLogger(ClientThread.class.getName()).log(Level.WARNING,
                    "Hubo un problema en el Thread del Cliente", ex);
        } finally {
            if (clientSocket != null) {
                try {
                    clientSocket.close();
                } catch (IOException ex) {
                    Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE,
                            "Hubo un problema al cerrar el Thread del Cliente", ex);
                }
            }
        }
    }
}
